package sbj.wizcore.common;


import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class FmHelper {

    /**
     * 23      *
     * 24      * TODO
     * 25      * <br>
     * 26      * @author kangxu2 2016-11-23
     * 27      *
     * 28      * @param fltFile  flt文件名
     * 29      * @param templatePath flt文件路径   src/template
     * 30      * @param datas 数据集合
     * 31      * @return
     * 32
     */
    public static String geneFileStr(String fltFile, Map<String, Object> datas) {

        Configuration cfg = new Configuration();
        try {


            cfg.setDirectoryForTemplateLoading(new File(FmHelper.class.getResource("/").getPath()));
            Template template = cfg.getTemplate(fltFile, Constants.ENCODING);
            template.setEncoding(Constants.ENCODING);

            StringWriter out = new StringWriter();

            template.process(datas, out);

            out.flush();
            out.close();

            return out.getBuffer().toString();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    public static void geneFile(String fltFile, Map<String, Object> datas, String outPutDir) {
        String resHtml = geneFileStr(fltFile, datas);
        FileWriter fw = null;
        try {

            File file = new File(outPutDir);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();

            fw = new FileWriter(outPutDir);
            fw.write(resHtml);
            fw.flush();

        } catch (IOException e) {
            System.out.println(e);
        }
    }


    public static void main(String args[]) {

        Map<String, Object> datas = new HashMap<String, Object>();
        datas.put("code", "ssss");

        System.out.println(FmHelper.geneFileStr("template.flt", datas));
    }
}
